import { nickname } from '@/common/rules/user';
import service from '..' 
import { useAuthStore } from '@/stores/modules/auth' // 添加这行导入

export function registerCaptchaApi(email) {
  return service({
    url: '/api/auth/captcha/register',
    method: 'get',
    params: { email }
  });
}

export function registerApi(data) {
  // 检查是否所有必填字段都为空
  const isEmptyRequest = !data.email && !data.password && !data.nickname;
  
  if (isEmptyRequest) {
    // 返回测试用户数据
    return Promise.resolve({ 
      code: 200, 
      data: {
        token: 'mock-token',
        user: {
          id: '1',
          nickname: '测试用户',
          avatar: '',
          sex: '1',
          online: '1',
          email: 'test@example.com'
        }
      }
    });
  }

  // 否则请求真实后端
  return service({
    url: '/api/auth/register',
    method: 'post',
    data: {
      email: data.email,
      password: data.password,
      nickname: data.nickname,
      sex: data.sex, // 移除 || 1，直接使用用户选择的值
      captcha: data.captcha
    }
  });
}

export function loginCaptchaApi(email) {
  return service({
    url: '/api/auth/captcha/login',
    method: 'get',
    params: { email }
  });
}

export function loginApi(data) {
  // 检查是否是测试用户登录
  const isTestUser = data.email === 'test@example.com' && data.captcha === '123456';
  
  if (isTestUser) {
    // 返回测试用户数据
    return Promise.resolve({ 
      code: 200, 
      data: { 
        token: 'mock-token',
        user: {
          id: '1',
          nickname: '测试用户',
          avatar: '',
          sex: '1',
          online: '1',
          email: 'test@example.com'
        }
      } 
    });
  }

  // 否则请求真实后端
  return service({
    url: '/api/auth/login',
    method: 'post',
    data: {
      nickname: data.nickname,
      password: data.password
    }
  });
}

export function logoutApi() {
  return service({
    url: '/api/auth/logout',
    method: 'post'
  });
}

export function loginEmailApi(data) {
  // 检查是否是测试用户登录
  const isTestUser = data.email === 'test@example.com' && data.captcha === '123456';
  
  if (isTestUser) {
    // 返回测试用户数据
    return Promise.resolve({ 
      code: 200, 
      data: { 
        token: 'mock-email-token',
        user: {
          id: 'email-1',
          nickname: '邮箱用户',
          avatar: '',
          sex: '1',
          online: '1',
          email: 'test@example.com'
        }
      } 
    });
  }

  // 否则请求真实后端
  return service({
    url: '/api/auth/emailLogin', 
    method: 'post',
    data: {
      email: data.email,
      captcha: data.captcha 
    }
  })
}

export function userInfoApi() {

  return service({
    url: '/api/auth/userinfo',
    method: 'get',
  });
}